<template>
  <el-dialog
      v-model="dialogVisible"
      title="批量导出个人获奖"
      width="80%"
      :before-close="handleClose"
  >
    <div class="export-content">
      <!-- 字段选择区域 -->
      <div class="field-selection">
        <p class="section-label">字段选择区域 <el-icon><QuestionFilled /></el-icon></p>
        <div class="field-tags">
          <el-tag
              v-for="field in fields"
              :key="field.key"
              class="field-tag"
              :effect="field.selected ? 'light' : 'plain'"
              @click="toggleField(field)"
          >
            {{ field.label }}
          </el-tag>
        </div>
      </div>

      <!-- 表格预览区域 -->
      <el-table
          :data="tableData"
          style="width: 100%"
          :border="true"
          class="export-table"
      >
        <el-table-column
            v-for="field in selectedFields"
            :key="field.key"
            :prop="field.key"
            :label="field.label"
            :min-width="field.width || 120"
        />
      </el-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleExport">下载Excel</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {exportAward} from "@/api/result/awardPersonal.js";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  personal: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue'])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const fields = ref([
  { key: 'nickName', label: '用户昵称', selected: true },  { key: 'title', label: '奖励名称', selected: true, width: 200 },
  { key: 'authorRank', label: '本人排名', selected: true },
  { key: 'awardLevel', label: '奖励等级', selected: true },
  { key: 'level', label: '级别', selected: true },
  { key: 'grantingUnit', label: '授予单位', selected: true },
  { key: 'awardTime', label: '获奖时间', selected: true },
  { key: 'remarks', label: '备注信息', selected: true },
  { key: 'authorInfo', label: '作者信息', selected: true, width: 200 },
  { key: 'syncStatus', label: '同步状态', selected: true },
  { key: 'createdAt', label: '创建时间', selected: true },
  { key: 'updatedAt', label: '更新时间', selected: true }

])

const selectedFields = computed(() => fields.value.filter(f => f.selected))

const tableData = ref([])

watch(() => props.personal, async (newPersonal) => {


        tableData.value = newPersonal.map(award => ({
          ...award,
          awardTime: formatDate(award.awardTime),
          createdAt: formatDate(award.createdAt),
          updatedAt: formatDate(award.updatedAt),
          authorInfo: formatAuthorInfo(award.authorInfo)
        }))


  }
, { immediate: true })

const toggleField = (field) => {
  field.selected = !field.selected
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleCancel = () => {
  dialogVisible.value = false
  ElMessage.info('已取消导出')
}

const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

const formatAuthorInfo = (authorInfo) => {
  if (!authorInfo || !Array.isArray(authorInfo)) return ''
  return authorInfo.map(author => `${author.name}(${author.identity})`).join(', ')
}

const handleExport = async () => {
  const selectedFields = fields.value.filter(f => f.selected)
  if (selectedFields.length === 0) {
    ElMessage.warning('请至少选择一个导出字段')
    return
  }
  const selectedFieldKeys = selectedFields.map(field => field.key)
  const exportData = tableData.value.map(award => {
    const filteredAward = {}
    selectedFieldKeys.forEach(key => {
      filteredAward[key] = award[key]
    })
    return filteredAward
  })
  try {
    // 这里需要替换为您的实际导出API
    const response = await exportAward({
      fields: selectedFields,
      data: exportData
    })
      const blob = response
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = 'exported_personal_awards.xlsx'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败: ' + error.message)
  }

  dialogVisible.value = false
}
</script>

<style scoped>
.export-content {
  padding: 20px 0;
}
.field-selection {
  margin-bottom: 24px;
}
.section-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}
.field-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.field-tag {
  cursor: pointer;
  user-select: none;
}
.field-tag:hover {
  border-color: #409eff;
}
.export-table {
  margin-top: 20px;
  border-radius: 4px;
}
:deep(.el-dialog__header) {
  margin-right: 0;
  border-bottom: 1px solid #dcdfe6;
}
:deep(.el-dialog__footer) {
  border-top: 1px solid #dcdfe6;
  padding: 20px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
